/**
 * 判断是否支付sticky, 用于减少性能消耗
 */
import { ComponentInternalInstance } from 'vue'

export default function useSupportSticky(instance: ComponentInternalInstance) {

  // 检测当前环境是否支持CSS Sticky
  const checkCSSStickySupport = async (selector: string): Promise<boolean> => {
    let stickyStatus: boolean = false
    // #ifdef H5
    // H5, 主流的浏览器都是支持css sticky
    stickyStatus = checkCSSStickyForH5()
    // #endif

    // 通过机型去判断
    stickyStatus = checkCSSStickyForPhoneOS()

    // #ifdef APP-VUE || MP-WEIXIN
    stickyStatus = await checkCSSStickyForAPPAndWX(selector)
    // #endif

    // #ifdef APP-NVUE
    // nvue是支持的
    stickyStatus = true
    // #endif
    return new Promise(resolve => {
      resolve(stickyStatus)
    })
  }

  // 根据机型判断是否支持
  const checkCSSStickyForPhoneOS = (): boolean => {
    // 获取手机对应的系统\操作系统名称和版本
    let { platform, system } = uni.getSystemInfoSync()
    const os = platform.toLowerCase()
    const osVersion = system
    if ((os === 'android' && Number(osVersion.replace('Android', '')) > 8) || (os === 'ios')) {
      return true
    }
    return false
  }

  // 在APP和微信小程序上，通过uni.createSelectorQuery判断是否支持sticky
  const checkCSSStickyForAPPAndWX = (selector: string): Promise<boolean> => {
    // 在方法内进行判断，避免生存无用代码
    // #ifdef APP-VUE || MP-WEIXIN
    return new Promise(resolve => {
      uni.createSelectorQuery().in(instance)
        .select(selector)
        .fields({
          computedStyle: ['position']
        }, () => {})
        .exec(res => {
          resolve('sticky' === res[0].position)
        })
    })
    // #endif
  }

  // H5通过创建元素的形式嗅探是否支持css sticky
  const checkCSSStickyForH5 = (): boolean => {
    // 在方法内进行判断，避免生存无用代码
    /* #ifdef H5 */
    const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
      vendorListLength = vendorList.length,
      stickElement = document.createElement('div');
    
    for (let i = 0; i < vendorList.length; i++) {
      stickElement.style.position = vendorList[i] + 'sticky'
      if (stickElement.style.position !== '') {
        return true
      }
    }
    return false
    /* #endif */
  }

  return {
    checkCSSStickySupport
  }
}